package com.oim.fx.view;

import java.awt.Color;
import java.io.File;
import java.util.Date;
import java.util.List;

import com.oim.core.app.AppContext;
import com.oim.core.bean.UserData;
import com.oim.core.business.box.PersonalBox;
import com.oim.core.business.manage.ImageManage;
import com.oim.core.business.sender.ChatSender;
import com.oim.core.common.AppConstant;
import com.oim.core.common.action.BackAction;
import com.oim.core.common.action.BackInfo;
import com.oim.core.common.app.view.AbstractView;
import com.oim.core.common.component.file.FileHandleInfo;
import com.oim.core.common.component.file.FileInfo;
import com.oim.core.common.util.ColorUtil;
import com.oim.core.net.message.data.UserChatHistoryData;
import com.oim.core.net.message.data.chat.Content;
import com.oim.core.net.message.data.chat.Item;
import com.oim.core.net.message.different.PageImpl;
import com.oim.core.net.message.query.ChatQuery;
import com.oim.core.net.server.Back;
import com.oim.fx.common.util.ContentUtil;
import com.oim.fx.ui.ChatHistoryFrame;
import com.oim.fx.ui.component.WaitingPanel;
import com.only.common.result.Info;
import com.only.common.util.OnlyDateUtil;
import com.only.general.annotation.parameter.Define;
import com.only.net.data.action.DataBackActionAdapter;

import javafx.application.Platform;
import javafx.scene.Node;
import javafx.scene.control.Label;
import javafx.util.Callback;

/**
 * @author: XiaHui
 * @date: 2017年4月11日 下午12:07:41
 */
public class UserChatHistoryViewImpl extends AbstractView implements UserChatHistoryView {

    ChatHistoryFrame frame;// = new ChatHistoryFrame();
    String userId;

    public UserChatHistoryViewImpl(AppContext appContext) {
        super(appContext);
        Platform.runLater(new Runnable() {
            @Override
            public void run() {
                frame = new ChatHistoryFrame();
                initEvent();
            }
        });
    }

    private void initEvent() {

        DataBackActionAdapter dataBackAction = new DataBackActionAdapter() {

            @Override
            public void lost() {
                showWaiting(true, WaitingPanel.show_result);
            }

            @Override
            public void timeOut() {
                showWaiting(true, WaitingPanel.show_result);
            }

            @Back
            public void back(Info info, @Define("sendUserId") String sendUserId, @Define("receiveUserId") String receiveUserId, @Define("contents") List<UserChatHistoryData> contents, @Define("page") PageImpl page) {
                setList(contents, page);
                showWaiting(false, WaitingPanel.show_waiting);
            }
        };

        initPage();
        frame.setPageFactory(new Callback<Integer, Node>() {

            @Override
            public Node call(Integer index) {

                int pageNumber = (index + 1);
                PersonalBox pb=appContext.getBox(PersonalBox.class);
        		UserData sendUser = pb.getUserData();
                PageImpl page = new PageImpl();
                page.setPageSize(30);
                page.setPageNumber(pageNumber);
                ChatSender ds = appContext.getSender(ChatSender.class);
                ds.queryUserChatLog(sendUser.getId(), (userId == null || "".equals(userId)) ? "00000" : userId, new ChatQuery(), page, dataBackAction);
                frame.showWaiting(true, WaitingPanel.show_waiting);
                return new Label("第" + pageNumber + "页");
            }
        });
    }

    public void setList(List<UserChatHistoryData> contents, PageImpl page) {
        StringBuilder div = new StringBuilder();
        div.append("<div>");
        if (null != contents) {
            for (UserChatHistoryData chd : contents) {
                UserData sendUserData = chd.getSendUserData();
                Content content = chd.getContent();
                String name = sendUserData.getNickname();
                String time = OnlyDateUtil.dateToDateTime(new Date(content.getTimestamp()));
                String greenColor = ColorUtil.getColorInHexFromRGB(32, 143, 62);
                String blueColor = ColorUtil.getColorInHexFromRGB(Color.blue.getRed(), Color.blue.getGreen(), Color.blue.getBlue());
                PersonalBox pb=appContext.getBox(PersonalBox.class);
        		UserData user = pb.getUserData();
                boolean isOwn = user.getId().equals(sendUserData.getId());

                String nameTag = ContentUtil.getInsertNameTag(name, isOwn ? greenColor : blueColor, time);
                div.append(nameTag);
                String contentTag = ContentUtil.getInsertContentTag(content);
                div.append(contentTag);
            }

        }
        div.append("</div>");
        Platform.runLater(new Runnable() {
            @Override
            public void run() {
                frame.setBodyHtml(div.toString());
                int totalPage = page.getTotalPage();
                frame.setTotalPage((totalPage <= 0 ? 1 : totalPage));
            }
        });

        PersonalBox pb=appContext.getBox(PersonalBox.class);
		UserData user = pb.getUserData();
        BackAction<List<FileHandleInfo>> backAction = new BackAction<List<FileHandleInfo>>() {

            @Override
            public void back(BackInfo backInfo, List<FileHandleInfo> list) {
                for (FileHandleInfo fd : list) {
                    FileInfo fi = fd.getFileInfo();
                    if (fd.isSuccess()) {
                        File file = (null != fi) ? fi.getFile() : null;
                        String name = (null != file) ? file.getName() : "";
                        String id = (null != fi) ? fi.getId() : "";
                        String appPath = AppConstant.userHome + "/" + AppConstant.app_home_path + "/" + user.getNumber() + "/image/" + name;

                        Platform.runLater(new Runnable() {
                            @Override
                            public void run() {
                                String path = "";

                                if (appPath.startsWith("/")) {
                                    path = "file:" + appPath;
                                } else {
                                    path = "file:/" + appPath;
                                }
                                frame.replaceImage(id, path);
                            }
                        });
                    } else {
                        String id = (null != fi) ? fi.getId() : "";
                        Platform.runLater(new Runnable() {
                            @Override
                            public void run() {
                                String tempImage = "Resources/Images/Default/ChatFrame/ImageLoading/image_download_fail.png";
                                File file = new File(tempImage);
                                if (file.exists()) {
                                    tempImage = file.getAbsolutePath();
                                }
                                frame.replaceImage(id, tempImage);
                            }
                        });
                    }
                }
            }
        };
        if (null != contents) {
            for (UserChatHistoryData chd : contents) {
                Content content = chd.getContent();
                ImageManage im = this.appContext.getManage(ImageManage.class);
                List<Item> items = ContentUtil.getImageItemList(content);
                im.downloadImage(items, backAction);
            }
        }
    }

    @Override
    public void setVisible(boolean visible) {
        Platform.runLater(new Runnable() {
            @Override
            public void run() {
                if (!isShowing()) {
                    initPage();
                }
                if (visible) {
                    frame.show();
                    frame.toFront();
                } else {
                    frame.hide();
                }
            }
        });
    }

    @Override
    public boolean isShowing() {
        return frame.isShowing();
    }

    public void showWaiting(boolean show, String key) {
        Platform.runLater(new Runnable() {
            @Override
            public void run() {
                frame.showWaiting(show, key);
            }
        });
    }

    public void setUserId(String userId) {
        this.userId = userId;
    }

    public void initPage() {
        frame.setPage(0, 10);
    }
}
